<?
class usersAjaxRoles extends ActionHandler
{
    function save_role()
    {
        global $dbLink, $user;
        if (!$user->isEnabledTo("write", $module->id)) die();
        if($_REQUEST["roleID"]=="") die(json_encode(array("success" => true)));
        $roleID = mysql_escape_string($_REQUEST["roleID"]);
        $role = new Role($roleID);
        $role->description = mysql_escape_string($_REQUEST["description"]);
        $role->save();
        echo json_encode(array("success" => true));
    }

    function set_role_perm()
    {
        if(!isset($_GET["role_id"])) die();
        $role = new Role(mysql_escape_string($_GET["role_id"]));
        foreach($_REQUEST["perm"] as $modID=>$permissions)
        {
           array_pop($permissions);
           $permissions = array_keys($permissions);
           $role->setModulePermissions($modID, $permissions);
        }
    }

    function get_role_perm()
    {
        $modules = getAllModules();
        if(!isset($_GET["roleID"])) die();
        $roleID = mysql_escape_string($_GET["roleID"]);
        $role = new Role($roleID);
        $form_items = array();
        foreach($modules as $mod) {
            $perms = $role->getModulePermissions($mod->_moduleID);
            $ar_permissions = array();
            foreach($mod->permissions as $k=>$v) {
                    $form_items["perm[".$mod->_moduleID."][".$k."]"] = false;
                    if(in_array($k, $perms))
                        $form_items["perm[".$mod->_moduleID."][".$k."]"] = true;
            }
        }

        $form_items["role_id"]=$roleID;
        echo json_encode(array("success"=>true, "data"=> $form_items));
    }

    function delete_role()
    {
        if (!$user->isEnabledTo("write", $module->id)) die();
        $roleID = mysql_escape_string($_REQUEST["roleID"]);
        $role = new Role($roleID);
        $role->delete();
        echo json_encode(array("success" => true));
    }

    function role_list()
    {
        global $dbLink;
        $table  = $GLOBALS["CONF"]["db"]["prefix"]."users_roles";
        $order  = mysql_escape_string($_REQUEST["sort"]) == "" ? "roleID" : mysql_escape_string($_REQUEST["sort"]);
        $dir    = mysql_escape_string($_REQUEST["dir"])  == "" ? "DESC" : mysql_escape_string($_REQUEST["dir"]);
        $sql = "SELECT * FROM ". $table ." ORDER BY ".$order." ".$dir;

        $res = mysql_query($sql, $dbLink);
        $data = array();
        while($row = mysql_fetch_array($res))
        {
            $role = new Role($row['roleID']);
            $data[] = array("roleID"=>$row['roleID'], "description"=>$row['description'], "users"=>implode(", ",$role->getUsers()));
        }
        echo json_encode(array("data"=> $data, "total"=>count($data)));
    }
}

?>
